from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone


class UserGroup(models.Model):
    """用户组模型"""
    name = models.CharField(max_length=100, unique=True, verbose_name='组名')
    description = models.TextField(blank=True, verbose_name='描述')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'user_groups'
        verbose_name = '用户组'
        verbose_name_plural = '用户组'

    def __str__(self):
        return self.name


class Role(models.Model):
    """角色模型"""
    name = models.CharField(max_length=100, unique=True, verbose_name='角色名')
    description = models.TextField(blank=True, verbose_name='描述')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'roles'
        verbose_name = '角色'
        verbose_name_plural = '角色'

    def __str__(self):
        return self.name


class Permission(models.Model):
    """权限模型"""
    name = models.CharField(max_length=100, unique=True, verbose_name='权限名')
    code = models.CharField(max_length=100, unique=True, verbose_name='权限代码')
    description = models.TextField(blank=True, verbose_name='描述')
    module = models.CharField(max_length=50, verbose_name='模块')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')

    class Meta:
        db_table = 'permissions'
        verbose_name = '权限'
        verbose_name_plural = '权限'

    def __str__(self):
        return self.name


class Menu(models.Model):
    """菜单模型"""
    name = models.CharField(max_length=100, verbose_name='菜单名')
    path = models.CharField(max_length=200, verbose_name='路径')
    component = models.CharField(max_length=200, blank=True, verbose_name='组件')
    icon = models.CharField(max_length=100, blank=True, verbose_name='图标')
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, verbose_name='父菜单')
    level = models.IntegerField(default=1, verbose_name='菜单层级', help_text='1=一级菜单, 2=二级菜单')
    sort_order = models.IntegerField(default=0, verbose_name='排序')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')

    class Meta:
        db_table = 'menus'
        verbose_name = '菜单'
        verbose_name_plural = '菜单'
        ordering = ['sort_order']

    def __str__(self):
        return self.name


class CustomUser(AbstractUser):
    """扩展用户模型"""
    full_name = models.CharField(max_length=100, blank=True, verbose_name='姓名')
    phone = models.CharField(max_length=20, blank=True, verbose_name='电话')
    avatar = models.ImageField(upload_to='avatars/', blank=True, verbose_name='头像')
    department = models.CharField(max_length=100, blank=True, verbose_name='部门')
    bio = models.TextField(blank=True, verbose_name='个人简介')
    user_groups = models.ManyToManyField(UserGroup, blank=True, verbose_name='用户组')
    roles = models.ManyToManyField(Role, blank=True, verbose_name='角色')
    last_login_ip = models.GenericIPAddressField(null=True, blank=True, verbose_name='最后登录IP')
    login_count = models.IntegerField(default=0, verbose_name='登录次数')
    # 个性化背景设置
    background_image = models.ImageField(upload_to='backgrounds/', blank=True, null=True, verbose_name='背景图片')
    background_settings = models.TextField(blank=True, default='{}', verbose_name='背景设置')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'users'
        verbose_name = '用户'
        verbose_name_plural = '用户'

    def __str__(self):
        return self.username


class RolePermission(models.Model):
    """角色权限关联模型"""
    role = models.ForeignKey(Role, on_delete=models.CASCADE, verbose_name='角色')
    permission = models.ForeignKey(Permission, on_delete=models.CASCADE, verbose_name='权限')
    access_level = models.CharField(
        max_length=20,
        choices=[('read', '只读'), ('write', '读写')],
        default='read',
        verbose_name='访问级别'
    )
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')

    class Meta:
        db_table = 'role_permissions'
        unique_together = ['role', 'permission']
        verbose_name = '角色权限'
        verbose_name_plural = '角色权限'


class MenuPermission(models.Model):
    """菜单权限关联模型"""
    menu = models.ForeignKey(Menu, on_delete=models.CASCADE, verbose_name='菜单')
    role = models.ForeignKey(Role, on_delete=models.CASCADE, verbose_name='角色')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')

    class Meta:
        db_table = 'menu_permissions'
        unique_together = ['menu', 'role']
        verbose_name = '菜单权限'
        verbose_name_plural = '菜单权限'


class LoginHistory(models.Model):
    """登录历史模型"""
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='用户')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(verbose_name='用户代理')
    login_time = models.DateTimeField(default=timezone.now, verbose_name='登录时间')
    is_success = models.BooleanField(default=True, verbose_name='是否成功')

    class Meta:
        db_table = 'login_history'
        verbose_name = '登录历史'
        verbose_name_plural = '登录历史'
        ordering = ['-login_time']


class UserGroupRole(models.Model):
    """用户组角色关联模型"""
    user_group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, verbose_name='用户组')
    role = models.ForeignKey(Role, on_delete=models.CASCADE, verbose_name='角色')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')

    class Meta:
        db_table = 'user_group_roles'
        unique_together = ['user_group', 'role']
        verbose_name = '用户组角色'
        verbose_name_plural = '用户组角色'

    def __str__(self):
        return f"{self.user_group.name} - {self.role.name}"
